package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class demo8TcpEchoClient {
    Socket socket = null;
    public demo8TcpEchoClient(String serverIp, int serverPort) throws IOException {
        socket = new Socket(serverIp, serverPort);
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner sc = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            while (true){
                System.out.println("->");
                //从控制台接收请求
                String request = sc.next();
                //将请求发送给服务器
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(request);
                writer.flush();
                //从服务器接收响应
                Scanner scanner = new Scanner(inputStream);
                String respond = scanner.next();
                //将响应打印到控制台
                System.out.println(respond);
            }
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        demo8TcpEchoClient demo8TcpEchoClient = new demo8TcpEchoClient("127.0.0.1", 9090);
        demo8TcpEchoClient.start();
    }
}
